import Vue from 'vue'
import Vuex from 'vuex'
import { setItem, getItem } from '@/utils/storage'
import { USERKEY, CHANNELKEY, HISTORYKEY } from '@/config/env.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: getItem(USERKEY),
    // 对用户的搜索历史进行持久化保存
    searchHis: getItem(HISTORYKEY)
  },
  mutations: {
    // 搜索历史修改
    setHis (state, val) {
      const index = state.searchHis.findIndex(v => v === val)
      if (index > -1) {
        state.searchHis.splice(index, 1)
      }

      state.searchHis.unshift(val)
      setItem(HISTORYKEY, state.searchHis)
    },
    // 删除所有历史
    removeAllHis (state) {
      state.searchHis = []
      setItem(HISTORYKEY, [])
    },
    // 删除某条历史条目
    removeHis (state, ind) {
      state.searchHis.splice(ind, 1)
      setItem(HISTORYKEY, state.searchHis)
    },
    setUser (state, newUser) {
      state.user = newUser
      setItem(USERKEY, newUser)
    },
    setNewToken (state, newToken) {
      state.user.token = newToken
      setItem(USERKEY, state.user)
    },
    setItemFn (data) {
      setItem(CHANNELKEY, data)
    }
  },
  actions: {},
  modules: {}
})
